<?php

declare (strict_types = 1);

namespace App\Service\Organziation;

use App\Constants\ErrorCode;
use App\Dao\AuthAdminLogDao;
use App\Dao\AuthDutyDao;
use App\Dao\AuthEmployeeDao;
use App\Exception\BusinessException;
use App\Model\AuthDuty;
use App\Utils\ApiUtils;
use Hyperf\DbConnection\Db;

class DutyService
{
    /**
     * 获取职位列表
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    function list(array $params) {
        if (isset($params['list_type']) && $params['list_type'] == 1) {
            $data = make(AuthDutyDao::class)->getByWhereTrait(['company_id' => $params['company_id']], ['id', 'name'])->toArray();
        } else if (isset($params['list_type']) && $params['list_type'] == 2) {
            //追加顶部数据
            $append = [
                'id' => AuthDuty::TOP_DUTY_ID,
                'name' => AuthDuty::TOP_DUTY_NAME,
            ];
            $data = make(AuthDutyDao::class)->getByWhereTrait(['company_id' => $params['company_id']], ['id', 'name'])->toArray();
            array_unshift($data, $append);
        } else {
            $map[] = [
                'company_id', "=", $params['company_id'],
            ];
            if (isset($params['name']) && $params['name'] !== "") {
                $map[] = [
                    'name', "like", "%{$params['name']}%",
                ];
            }

            if (isset($params['pid']) && $params['pid'] !== "") {
                $map[] = [
                    'pid', "=", $params['pid'],
                ];
            }

            if (isset($params['add_time_start']) && $params['add_time_start'] !== "") {
                $map[] = [
                    'add_time', ">=", $params['add_time_start'],
                ];
            }

            if (isset($params['add_time_end']) && $params['add_time_end'] !== "") {
                $map[] = [
                    'add_time', "<=", $params['add_time_end'],
                ];
            }

            $data = make(AuthDutyDao::class)->getByOrderByPid($map, $params['page'], $params['pageSize']);
            $count = make(AuthDutyDao::class)->countByWhereTrait($map);
            $pid = make(AuthDutyDao::class)->getByWhereTrait(['company_id' => $params['company_id']], ['id', 'name', 'pid'])->keyBy('id')->toArray();
            foreach ($data as $key => $val) {
                $data[$key]['pid_name'] = $data[$key]['pid'] ? $pid[$data[$key]['pid']]['name'] : AuthDuty::TOP_DUTY_NAME;
            }
            $data = array_values($data);
        }

        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功', $data, $count ?? 1);
    }

    /**
     * 添加职位
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    public function addDuty(array $params)
    {
        if (make(AuthDutyDao::class)->existsByWhereTrait([['name', '=', $params['name']], ['company_id', '=', $params['company_id']]])) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '已存在相同职位名称');
        }
        if ($params['pid'] != AuthDuty::TOP_DUTY_ID) {
            $duty = make(AuthDutyDao::class)->findTrait($params['pid']);
            if ($duty) {
                $params['grade'] = $duty->grade + 1;
            } else {
                throw new BusinessException(ErrorCode::ERR_BUESSUS, '上级id设定异常');
            }
        }
        make(AuthDutyDao::class)->createTrait($params);
        make(AuthAdminLogDao::class)->addLog('新增岗位信息' . json_encode($params, JSON_UNESCAPED_UNICODE));
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功');
    }

    /**
     * 修改职位
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    public function editDuty(array $params)
    {
        if (make(AuthDutyDao::class)->existsByWhereTrait([['name', '=', $params['name']], ['company_id', '=', $params['company_id']], ['id', '!=', $params['duty_id']]])) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '已存在相同职位名称');
        }
        $logInfo = make(AuthDutyDao::class)->findTrait($params['duty_id'])->toJson(JSON_UNESCAPED_UNICODE);
        if ($params['pid'] != AuthDuty::TOP_DUTY_ID) {
            $duty = make(AuthDutyDao::class)->findTrait($params['pid']);
            if ($duty) {
                $params['grade'] = $duty->grade++;
            } else {
                throw new BusinessException(ErrorCode::ERR_BUESSUS, '上级id设定异常');
            }
        }
        $params['id'] = $params['duty_id'];
        make(AuthDutyDao::class)->updateByIdTrait($params);
        make(AuthAdminLogDao::class)->addLog('编辑了岗位信息' . json_encode($params, JSON_UNESCAPED_UNICODE) . ' 原岗位信息' . $logInfo);
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功');
    }

    /**
     * 删除职位
     *
     * @Author czm
     * @DateTime 2020-09-28
     * @param array $params
     * @return void
     */
    public function delDuty(array $params)
    {
        if ($params['operation_confirm'] != 2) {
            return ApiUtils::send(ErrorCode::SUCCESS, '请确认删除！该操作将清除与员工关联', [false]);
        }
        if (make(AuthDutyDao::class)->existsByWhereTrait(['pid' => $params['duty_id']])) {
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '存在下级无法删除');
        }
        Db::beginTransaction();
        try {
            $params['id'] = $params['duty_id'];
            $params['is_del'] = 2;
            make(AuthDutyDao::class)->updateByIdTrait($params);
            make(AuthEmployeeDao::class)->updateByWhereTrait(['duty_id' => $params['duty_id']], ['duty_id' => 0]);
            make(AuthAdminLogDao::class)->addLog('删除岗位' . json_encode($params, JSON_UNESCAPED_UNICODE));
            Db::commit();
        } catch (\Throwable $t) {
            Db::rollBack();
            throw new BusinessException(ErrorCode::ERR_BUESSUS, '网络异常 数据写入失败');
        }
        return ApiUtils::send(ErrorCode::SUCCESS, '操作成功');
    }
}
